package com.zyk.leetcode;

import com.zyk.util.ListUtil;

/**
 * @author zhangsan
 * @date 2021/4/26 17:40
 */
public class C24 {


    public static ListNode swapPairs(ListNode head) {
        ListNode p = new ListNode(-1);
        p.next = head;
        ListNode next = null, pre = p;
        while (head != null && head.next != null) {
            next = head.next;   // 记录好下一个, 也就是新头

            head.next = next.next;  // 调整心头与就头
            next.next = head;
            pre.next = next;

            pre = head;         // pre来到新尾巴
            head = head.next;   // 去新尾巴的下一个
        }
        return p.next;
    }

    public static void swap(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) return;
        l1.next = l2.next;
        l2.next = l1;
    }

    // for test
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};
        ListNode head = ListUtil.generateList(arr);
        head = swapPairs(head);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

}
